package com.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.model.Users;

public class UsersService {

	public String map2Json(Controller controller) {
		int page = controller.getParaToInt("page");
		int rows = controller.getParaToInt("rows");
		String sort = controller.getPara("sort", "id");
		String order = controller.getPara("order", "asc");
		Page<Users> pages = Users.dao.usersPaginate(page, rows, sort, order);
		int total = pages.getTotalRow();
		Users.dao.put("total", total);
		List<?> list = pages.getList();
		Map<String, Object> map = new HashMap<>();
		map.put("rows", list);
		map.put("total", total);
		String str = JsonKit.toJson(map, 3);
		return str;
	}
	
	public Object[] deleteUsers(Controller controller) {
		String urlPara = controller.getPara();
		String[] para = urlPara.split("-");
		String msg = null;
		boolean flag = false;
		int delnum = 0;
		for (int i = 0; i < para.length; i++) {
			flag = Db.deleteById("users", "id", Integer.parseInt(para[i]));
			delnum++;
		}
		if (flag) {
			msg = "成功删除"+delnum+"个用户！";
		} else {
			msg = "删除失败";
		}
		Object[] obj = new Object[]{msg,flag};
		return obj;
	}
	
	public String editUsers(String id){
		Record record = Db.findById("users", Integer.parseInt(id));
		return record.toJson();
	}
}
